﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace WeChatParking.Web.Controllers
{
    public class BaseController : Controller
    {
        #region 返回Json结果

        public ActionResult OK(string message = "")
        {
            return ToJsonResult(true, message);
        }

        public ActionResult Fail(string message)
        {
            return ToJsonResult(false, message);
        }

        public ActionResult ToJsonResult(bool success, string message, object data = null)
        {
            return Json(new { Code = success ? 1 : 0, Message = message, Data = data });
        }

        #endregion

        #region jqgrid
        /// <summary>
        /// 分页
        /// </summary>
        /// <returns></returns>
        protected Entity.BaseFilter GetPageInfo()
        {
            var form = Request.Form;
            Entity.BaseFilter fiter = new Entity.BaseFilter()
            {
                page = Util.Conv.ToInt(form["page"]),
                rows = Util.Conv.ToInt(form["rows"], 20),
                sort = form["sidx"],
                asc = !string.Equals(form["sord"], "desc")
            };
            return fiter;
        }

        protected ActionResult ToGridJson<T>(Entity.PageList<T> data, object userData = null)
        {
            var d = new
            {
                rows = data.DataList,
                records = data.Total,
                total = data.TotalPage,
                page = data.Page,
                userdata = userData
            };
            return Json(d);
        }

        #endregion

        #region WxSession

        const string SESSION_USERID_KEY = "SESSION_USERID_KEY";


        const string SESSION_OPENID_KEY = "SESSION_OPENID_KEY";


        const string SESSION_OAUTHTYPE_KEY = "SESSION_OAUTHTYPE_KEY";


        /// <summary>
        /// Wx当前用户ID
        /// </summary>
        protected int CurrentUserID
        {
            get
            {
                var x = Util.Session.GetSession<int>(SESSION_USERID_KEY);
                return x;
            }
            set
            {
                Util.Session.SetSession(SESSION_USERID_KEY, value);
            }
        }

        /// <summary>
        /// Wx当前openid
        /// </summary>
        protected string CurrentOpenId
        {
            get
            {
                return Util.Session.GetSessionStr(SESSION_OPENID_KEY);
            }
            set
            {
                Util.Session.SetSession(SESSION_OPENID_KEY, value);
            }
        }

        /// <summary>
        /// Wx当前用户鉴权类型
        /// </summary>
        protected WeChatParking.Entity.Enums.OAuthUserType OAuthUserType
        {
            get
            {
                return Util.Session.GetSession<Entity.Enums.OAuthUserType>(SESSION_OAUTHTYPE_KEY);
            }
            set
            {
                Util.Session.SetSession(SESSION_OAUTHTYPE_KEY, value);
            }
        }

        #endregion

        /// <summary>
        /// 从cookie中设置当前Wx用户。
        /// </summary>
        /// <returns>是否设置成功</returns>
        protected bool InitUserFromCookie(string enterId)
        {
            if (string.IsNullOrEmpty(enterId) || Request == null || Request.Cookies == null)
                return false;

            try
            {
                string cookieKey = "LOGIN_USER_QY" + enterId;
                var cookie = Request.Cookies.Get(cookieKey);
                if (cookie != null && !string.IsNullOrWhiteSpace(cookie.Value))
                {
                    var arr = cookie.Value.Split(new char[] { '$' }, 3, StringSplitOptions.RemoveEmptyEntries);
                    if (arr.Length == 3)
                    {
                        this.OAuthUserType = (Entity.Enums.OAuthUserType)Int32.Parse(arr[0]);
                        this.CurrentUserID = Int32.Parse(arr[1]);
                        this.CurrentOpenId = arr[2];
                        return true;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                Core.LogHelper.Error(ex, "从cookie中设置当前用户");
                return false;
            }

        }
        /// <summary>
        /// cookie中设置当前Wx用户。
        /// </summary>
        /// <param name="enterId">企业ID</param>
        protected void SetCurrentUserToCookie(string enterId)
        {
            try
            {
                string cookieKey = "LOGIN_USER_QY" + enterId;
                var cookie = Response.Cookies.Get(cookieKey);
                if (cookie == null)
                {
                    cookie = new HttpCookie(cookieKey);
                    Response.Cookies.Add(cookie);
                }
                cookie.Name = cookieKey;
                cookie.Value = string.Format("{0}${1}${2}", (int)this.OAuthUserType, this.CurrentUserID, this.CurrentOpenId);
                cookie.Expires = DateTime.Now.AddDays(30);
            }
            catch (Exception ex)
            {
                Core.LogHelper.Error(ex, "设置当前用户信息到cookie");
            }

        }
        /// <summary>
        /// 重新登录
        /// </summary>
        /// <param name="enterId"></param>
        protected void ClearCurrentUserCookie(string enterId)
        {
            try
            {
                string cookieKey = "LOGIN_USER_QY" + enterId;
                var cookie = Response.Cookies.Get(cookieKey);
                if (cookie != null)
                    cookie.Expires = DateTime.Now.AddDays(-1);
            }
            catch (Exception ex)
            {
                Core.LogHelper.Error(ex, "清除当前用户信息的cookie");
            }
        }

        /// <summary>
        /// 设置验证码和验证码的时效
        /// </summary>
        /// <param name="YZM"></param>
        protected void SetYZM(int YZM)
        {
            Response.Cookies["YZM"].Value = YZM.ToString();
            Response.Cookies["YZM"].Expires = DateTime.Now.AddMinutes(30);
        }
        /// <summary>
        /// 获取验证码
        /// </summary>
        protected int GetYZM()
        {
            string _yzm = HttpContext.Request.Cookies["YZM"].Value;
            return int.Parse(_yzm != null && _yzm != "" ? _yzm : "0");
        }
    }

    public class AdminBaseController : BaseController
    {
        /// <summary>
        /// 获取当前登陆用户code
        /// </summary>
        /// <returns></returns>
        protected string GetCurrentLoginUserID()
        {
            try
            {
                return HttpContext.Session["UserCode"].ToString();
            }
            catch (Exception)
            {
                Redirect("~/Admin/Login");
                return "";
            }
        }
        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="user"></param>
        protected void OnLogin(Entity.User_info user)
        {
            HttpContext.Session["UserID"] = user.UserId;
            HttpContext.Session["EnterpriseID"] = user.EnterpriseID;
            HttpContext.Session["UserCode"] = user.UserCode;
            FormsAuthentication.SetAuthCookie(user.UserCode, false);
        }
        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        protected void OnLogoff()
        {
            Session.Abandon();
            System.Web.Security.FormsAuthentication.SignOut();
            Util.Session.RemoveAll();
        }
        /// <summary>
        /// 获取当前登录用户
        /// </summary>
        public WeChatParking.Entity.User_info LoginUser
        {
            get
            {
                WeChatParking.Entity.User_info user = null;
                string userCode = this.GetCurrentLoginUserID();
                if (userCode.Length == 0) return null;
                user = new Core.BLL.User_info().GetUser(userCode);

                return user;
            }
        }
        /// <summary>
        /// 获取当前用户的企业ID  0是超级管理员
        /// </summary>
        /// <returns></returns>
        protected int GetEnterpriseID()
        {
            var user = this.LoginUser;
            if (user != null)
                return user.UserName == "admin" ? 0 : user.EnterpriseID;
            else
                return 10001;


        }
    }
}
